package com.example.gzysmartcity.ui.fragment.me;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.gzysmartcity.App;
import com.example.gzysmartcity.MyLocationListener;
import com.example.gzysmartcity.R;
import com.example.gzysmartcity.databinding.FragmentMeBinding;
import com.example.gzysmartcity.databinding.PopuCleanBinding;
import com.example.gzysmartcity.databinding.PopuCommitXcPzBinding;
import com.example.gzysmartcity.repository.model.MyUser;
import com.example.gzysmartcity.ui.activity.LoginActivity;
import com.example.gzysmartcity.ui.base.BaseFragment;
import com.example.gzysmartcity.utils.NetworkUtil;
import com.example.gzysmartcity.utils.PopupUntil;
import com.example.gzysmartcity.viewmodel.MeViewModel;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.List;

public class MeFragment extends BaseFragment<FragmentMeBinding> implements View.OnClickListener {

    private MeViewModel meViewModel;
    private List<MyUser> myUserList;
    private final int ACTION_IMAGE_CAPTURE_TX = 1;
    private final int ACTION_PICK_TX = 2;
    private final int ACTION_IMAGE_CAPTURE_Back = 11;
    private final int ACTION_PICK_Back = 22;
    private SharedPreferences spPerson;
    private String imgName;
    private PopupUntil mUntilpz;

    @Override
    protected FragmentMeBinding viewBinding() {
        return FragmentMeBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        meViewModel = new ViewModelProvider(this).get(MeViewModel.class);
        b.tvMeExit.setOnClickListener(this);
        b.tvMeAdress.setOnClickListener(this);
        b.tvPersonality.setOnClickListener(this);
        b.tvMeBackset.setOnClickListener(this);
        b.btnSetting.setOnClickListener(this);
        b.btnMeExit.setOnClickListener(this);
        b.tvMeBirthday.setOnClickListener(this);
        b.touxiangImage.setOnClickListener(this);
        b.tvMeBackgcolor.setOnClickListener(this);
        spPerson = requireActivity().getSharedPreferences("me", Context.MODE_PRIVATE);
        b.tvMeAddressText.setText(spPerson.getString("city", ""));
        b.tvMeBacksetText.setText(SPUtils.getInstance("theme", Context.MODE_PRIVATE).getString("themeName", ""));
        if (NetworkUtil.userId == null) {
            b.btnMeExit.setText("进行登录");
        } else {
            meViewModel.loadAllMyUserDB();
            myUserList = meViewModel.getMyUserList();
            if (myUserList.size() != 0) {
                b.btnMeName.setText(myUserList.get(0).getUserName());
            }
            if (!spPerson.getString("personality", "").equals("")) {
                b.btnMeContent.setText(spPerson.getString("personality", ""));
            }
            b.tvMeBirthdayText.setText(spPerson.getString("birthbay", ""));
            b.btnMeExit.setText("退出登录");
            if (!spPerson.getString("back", "").equals("")) {
                Glide.with(requireContext()).load(spPerson.getString("back", "")).into(b.backMe);
            }
            if (!spPerson.getString("tx", "").equals("")) {
                Glide.with(requireContext()).load(spPerson.getString("tx", "")).into(b.touxiangImage);
            }
        }
        MyLocationListener.getLiveData().observe(getViewLifecycleOwner(), city -> {
            if (city != null) {
                CityPicker.from(MeFragment.this)
                        .locateComplete(new LocatedCity(city.getCity(), city.getProvince(), city.getAdcode()), LocateState.SUCCESS);
                App.stop();
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (!spPerson.getString("personality", "").equals("")) {
                b.btnMeContent.setText(spPerson.getString("personality", ""));
            }
        }
    }

    @SuppressLint({"SetTextI18n", "NonConstantResourceId"})
    @Override
    public void onClick(View v) {
        //点击【退出登录】后重置当页包含的个人信息，并且点击底部导航栏“主页”和“创意设计”会Toast提示【您还未登录】
        //在登录情况下，点击【注销登录】清除当页信息，并跳转到登录页面
        //1.在未登录情况下，点击【头像】【生日】【个性签名】【注销登录】Toast提示【您还未登录】
        int id = v.getId();
        if (NetworkUtil.userId == null) {
            if (v == b.btnMeExit) {
                startActivity(new Intent(requireActivity(), LoginActivity.class));
                requireActivity().finish();
                return;
            } else if (id == R.id.tv_me_backgcolor || id == R.id.tv_me_birthday || id == R.id.touxiang_image || id == R.id.tv_personality || id == R.id.tv_me_exit) {
                ToastUtils.showShort("您还未登录");
                return;
            }
        }
        switch (id) {
            case R.id.tv_me_exit:
                PopupUntil popupUntil = new PopupUntil();
                PopuCleanBinding popuCleanBinding = PopuCleanBinding.inflate(getLayoutInflater());
                popupUntil.getPopupDataByView(popuCleanBinding.getRoot(), requireContext());
                popuCleanBinding.tvCleanTitle.setText("请谨慎注销");
                popuCleanBinding.tvCleanContent.setText("注销后将会删除全部的账号信息和记录且无法恢复！");
                popuCleanBinding.tvCleanNo.setOnClickListener(v1 -> popupUntil.closePopup());
                popuCleanBinding.tvCleanYes.setOnClickListener(v1 -> {
                    SPUtils.getInstance("User", Context.MODE_PRIVATE).clear();
                    NetworkUtil.userId = null;
                    popupUntil.closePopup();
                    meViewModel.deleteMyUserDB(myUserList);
                    myUserList.clear();
                    b.touxiangImage.setImageResource(R.drawable.touxiang);
                    b.backMe.setBackgroundResource(R.color.white);
                    b.tvMeAddressText.setText("");
                    spPerson.edit().clear().apply();
                    startActivity(new Intent(requireActivity(), LoginActivity.class));
                    requireActivity().finish();
                });
                break;
            case R.id.tv_me_adress:
                cityPicker();
                break;
            case R.id.tv_personality:
                jumpHide(PersonalityFragemnt.class, null, null);
                break;
            case R.id.tv_me_backset:
                jump(ThemeFragment.class, null, null);
                break;
            case R.id.btn_setting:
                jump(SettingFragment.class, null, null);
                break;
            case R.id.btn_me_exit:
                //清除登录账号与密码
                SPUtils.getInstance("User").put("checkLogin", false);
                NetworkUtil.userId = null;
                b.btnMeName.setText("未登录");
                b.btnMeContent.setText("个性签名");
                b.btnMeExit.setText("进行登录");
                b.touxiangImage.setImageResource(R.drawable.touxiang);
                b.backMe.setImageResource(R.color.white);
                b.tvMeBirthdayText.setText("");
                b.tvMeAddressText.setText("");
                spPerson.edit().clear().apply();
                meViewModel.deleteMyUserDB(myUserList);
                myUserList.clear();
                break;
            case R.id.tv_me_birthday:
                new DatePickerDialog(requireContext(), (view, year, monthOfYear, dayOfMonth) -> {
                    b.tvMeBirthdayText.setText(year + "年" + monthOfYear + "月" + dayOfMonth + "日");
                    spPerson.edit().putString("birthbay", b.tvMeBirthdayText.getText().toString().trim()).apply();
                }, 2001, 1, 1).show();
                break;
            case R.id.touxiang_image:
                PopuPaiZao(ACTION_IMAGE_CAPTURE_TX, ACTION_PICK_TX);
                break;
            case R.id.tv_me_backgcolor:
                PopuPaiZao(ACTION_IMAGE_CAPTURE_Back, ACTION_PICK_Back);
                break;
        }
    }

    private void PopuPaiZao(int pictureId, int xiangCeId) {
        mUntilpz = new PopupUntil();
        PopuCommitXcPzBinding pzBinding = PopuCommitXcPzBinding.inflate(getLayoutInflater());
        mUntilpz.getPopupDataByView(pzBinding.getRoot(), requireActivity());
        pzBinding.popuCancel.setOnClickListener(v1 -> {
            mUntilpz.closePopup();
        });
        pzBinding.popuPicture.setOnClickListener(v1 -> {
//                    拍照
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File fileDir = new File(Environment.getExternalStorageDirectory(), "Pictures");
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            imgName = "IMG_" + System.currentTimeMillis() + ".jpg";
            String fileName = fileDir.getAbsolutePath() + "/" + imgName;
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, imgName);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Pictures");
            } else {
                contentValues.put(MediaStore.Images.Media.DATA, fileName);
            }
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
            Uri uri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            try {
                startActivityForResult(intent, pictureId);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showShort("此设备没有摄像机");
            }

        });
        pzBinding.popuXiangce.setOnClickListener(v1 -> {
//                    相册
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            try {
                startActivityForResult(intent, xiangCeId);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.showShort("此设备没有图库");
            }
        });
    }

    @Override
    protected String setTitle() {
        return null;
    }

    @Override
    protected boolean showBack() {
        return false;
    }

    @Override
    protected Boolean showBottom() {
        return true;
    }

    @SuppressLint("Range")
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ACTION_PICK_Back://背景相册
                if (data == null) return;
                Cursor cursor = requireContext().getContentResolver().query(data.getData(), new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                cursor.moveToFirst();
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                Glide.with(requireContext()).load(path).into(b.backMe);
                spPerson.edit().putString("back", path).apply();
                mUntilpz.closePopup();
                cursor.close();
                ToastUtils.showShort("背景更换成功");
                break;
            case ACTION_IMAGE_CAPTURE_Back://背景拍照
                try {
                    String selection = MediaStore.Images.Media.DISPLAY_NAME + "=? ";
                    Cursor cursor2 = requireContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA}, selection, new String[]{imgName}, null);
                    if (cursor2 != null && cursor2.moveToFirst()) {
                        cursor2.moveToFirst();
                        String path2 = cursor2.getString(cursor2.getColumnIndex(MediaStore.Images.Media.DATA));
                        Glide.with(requireContext()).load(path2).into(b.backMe);
                        spPerson.edit().putString("back", path2).apply();
                        mUntilpz.closePopup();
                        cursor2.close();
                    }
                    ToastUtils.showShort("背景更换成功");
                } catch (Exception e) {
                    ToastUtils.showShort(e.toString());
                    e.printStackTrace();
                }
                break;
            case ACTION_PICK_TX://头像相片
                if (data == null) return;
                Cursor cursorTX = requireContext().getContentResolver().query(data.getData(), new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                cursorTX.moveToFirst();
                String pathTX = cursorTX.getString(cursorTX.getColumnIndex(MediaStore.Images.Media.DATA));
                Glide.with(requireContext()).load(pathTX).into(b.touxiangImage);
                spPerson.edit().putString("tx", pathTX).apply();
                mUntilpz.closePopup();
                cursorTX.close();
                ToastUtils.showShort("头像更换成功");
                break;
            case ACTION_IMAGE_CAPTURE_TX://头像拍照
                try {
                    String selection = MediaStore.Images.Media.DISPLAY_NAME + "=? ";
                    Cursor cursor2 = requireContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA}, selection, new String[]{imgName}, null);
                    if (cursor2 != null && cursor2.moveToFirst()) {
                        cursor2.moveToFirst();
                        String path2 = cursor2.getString(cursor2.getColumnIndex(MediaStore.Images.Media.DATA));
                        Glide.with(requireContext()).load(path2).into(b.touxiangImage);
                        spPerson.edit().putString("tx", path2).apply();
                        mUntilpz.closePopup();
                        cursor2.close();
                    }
                    ToastUtils.showShort("头像更换成功");
                } catch (Exception e) {
                    ToastUtils.showShort(e.toString());
                    e.printStackTrace();
                }
                break;

        }
    }


    private void cityPicker() {
        CityPicker.from(MeFragment.this) //activity或者fragment
                .enableAnimation(true)    //启用动画效果，默认无
                .setLocatedCity(null)  //APP自身已定位的城市，传null会自动定位（默认）
                .setHotCities(meViewModel.getHotCities())    //指定热门城市
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        String name = data.getName();
                        ToastUtils.showShort(name);
                        spPerson.edit().putString("city", name).apply();
                        b.tvMeAddressText.setText(name);
                    }

                    @Override
                    public void onCancel() {
                        ToastUtils.showShort("取消选择");
                    }

                    @Override
                    public void onLocate() {
                        App.start();
                    }
                }).show();
    }
}